package com.heima.springai.service;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;

public class VoiceService {
    private static final String PY_URL = "http://localhost:5000";

    /* 1. 浏览器发来的音频 -> Python ASR -> 文本 */
    public static String asr(MultipartFile audio) throws IOException {
        Path tmp = Files.createTempFile("rec", ".webm");
        audio.transferTo(tmp.toFile());
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("audio", new FileSystemResource(tmp.toFile()));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> req = new HttpEntity<>(body, headers);
        return new RestTemplate().postForObject(PY_URL + "/asr", req, String.class);
    }

    /* 2. 文本 -> Python TTS -> wav 文件 */
    public static byte[] tts(String text) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> req = new HttpEntity<>("{\"text\":\"" + text + "\"}", headers);
        return new RestTemplate().postForObject(PY_URL + "/tts", req, byte[].class);
    }
}
